"""" 
Copyright 2009 Texas A&M University
 
Licensed under the Apache License, Version 2.0 (the "License"); you may not use 
this file except in compliance with the License. You may obtain a copy of the 
License at

http://www.apache.org/licenses/LICENSE-2.0
  
Unless required by applicable law or agreed to in writing, software distributed 
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
CONDITIONS OF ANY KIND, either express or implied. See the License for the 
specific language governing permissions and limitations under the License.
"""
import zope.interface

from meercat.interfaces import IMetadata

from meercat.mapreduce import interfaces
from meercat.mapreduce.exceptions import *
from meercat.mapreduce.mappers.base import BaseMapper



class ChainedMapper(BaseMapper):
    zope.interface.implements(interfaces.IChainedMapper)
    
    def __init__(self, source_format):
        """ The transformation should be a tuple like (source, destination) """
        self._chain = []
        self._source_format = source_format
        self._destination_format = None
    
    def append(self, mapper):
        if not interfaces.IMapper.providedBy(mapper):
            raise MapperError(u'Transformers must implement the IMapper '
                              'interface')
        
        input = self._destination_format
        
        if input is None:
            input = self._source_format
        
        try:
            output = mapper.getOutputFormat(input)
        except MapperError:
            raise MapperError(u'Mapper does not accept the current output of '
                              'the mapper chain')
        
        self._destination_format = output
        self._chain.append(mapper)
    
    def getFormats(self):
        return [(self._source_format, self._destination_format)]
    
    def map(self, metadata):
        self._validate(metadata)
        self.getOutputFormat(metadata.getFormat())
        
        for mapper in self._chain:
            if metadata:
                metadata = mapper.map(metadata)
        
        return metadata
